package com.ruoyi.system.task;


import lombok.extern.slf4j.Slf4j;

import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.*;
import java.util.*;

/**
 * @author xu wei
 * @version 1.0
 * @date 2023/10/30
 * @since jdk-1.8
 */
@Slf4j
public class ByExportProcessor {

    //db碎片化工具的frag命令
    private static String FRAG = "frag";
    //db碎片化工具的export命令
    private static String EXPORT = "export";
    //db碎片化工具执行环境 windows
    private static String WINDOW = "win";
    //db碎片化工具执行环境 linux
    private static String LINUX = "linux";

    private static String TABLEDIR = "table";
    private static String TABLEFIX = ".xlsx";
    //当前操作人
    private String userId;
    private ByExportProcessorHelper byExportProcessorHelper;

    public ByExportProcessor() {
    }

    public ByExportProcessor(String userId) {
        if (null == userId) {
            // if the username is null, set the default user as "kngc";
            this.userId = "1";
        } else {
            this.userId = userId;
        }
        byExportProcessorHelper = new ByExportProcessorHelper();
    }

//    /**
//     * 解析result.xml文件
//     *
//     * @param result 解析出的result.xml文件
//     * @param entity 封装的原数据
//     * @return
//     */
//    public Map<String, List<ChapterCata>> doHandleXML(File result, KnowledgeItem entity) {
//        Map<String, List<ChapterCata>> res = new HashMap<>();
//        LinkedList<String> reverse = new LinkedList<>();
//        BufferedReader reader = null;
//        try {
//            reader = new BufferedReader(new InputStreamReader(Files.newInputStream(result.toPath())));
//            String line;
//            while ((line = reader.readLine()) != null) {
//                reverse.addFirst(line.trim());
//            }
//        } catch (Exception e) {
//            log.error("读取文件失败" + e.getMessage());
//            e.printStackTrace();
//        } finally {
//            if (reader != null) {
//                try {
//                    reader.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        //章节段落
////        chapterProcess(res, entity, reverse);
//        //表格
//        Collections.reverse(reverse);
//        //tableProcess(res, reverse);
//        return res;
//    }

    /**
     * 解析result.xml中的表格
     *
     * @param res      最终返回的结果map
     * @param lineList result.xml解析出的一行行的文本list集合
     */
    private void tableProcess(Map<String, List<String>> res, List<String> lineList) {
        StringBuffer table = new StringBuffer();
        boolean begin = false;
        List<String> tableList = new ArrayList<>();
        for (String line : lineList) {
            if (line.trim().contains("<table")) {
                begin = true;
            }
            if ("</table>".equals(line.trim())) {
                begin = false;
                table.append(line.trim());
                tableList.add(table.toString());
                table = new StringBuffer();
            }
            if (begin) {
                table.append(line.trim());
            }
        }
        if (!tableList.isEmpty()) {
            res.put("tableList", tableList);
        }

    }
//
//    /**
//     * 解析xml中章节段落 叙逐行倒解析
//     *
//     * @param res      最终返回的结果map
//     * @param lineList result.xml解析出的一行行的文本list集合
//     */
//    private void chapterProcess(Map<String, List<ChapterCata>> res, KnowledgeItem entity, LinkedList<String> lineList) {
//        net.cnki.cscp.task.HprdcpXmlProcessorHelper helper = new net.cnki.cscp.task.HprdcpXmlProcessorHelper();
//        LinkedList<ChapterCata> chapterList = new LinkedList<>();
//        LinkedList<String> cataList = new LinkedList<>();
//        StringBuilder chapter = new StringBuilder();
//        String regexP = "<p id=\"\\d+\">[1-9][\\.|\\s|\\u3001|\\u4e00-\\u9fa5|\\(|\\（](.*?)<\\/p>";
//        String regexTitle = "<title>[1-9][\\.|\\s|\\u3001|\\u4e00-\\u9fa5|\\(|\\（](.*?)<\\/title>";
//        Pattern patternP = Pattern.compile(regexP);
//        Pattern patternTitle = Pattern.compile(regexTitle);
//        //倒叙解析
//        for (String itemLine : lineList) {
//            Matcher matcherP = patternP.matcher(itemLine);
//            Matcher matcherTitle = patternTitle.matcher(itemLine);
//            String text = processorHelper.getTextFromSingleXML(itemLine);
//            if (StringUtils.isNotEmpty(text)) {
//                if ((matcherP.find() || matcherTitle.find()) && text.length() < 30) {//超过30长度默认不是目录
//                    int compare = -1;
//                    if (!cataList.isEmpty()) {
//                        String lastCata = helper.getOnlyDigits(helper.getTextFromSingleXML(cataList.getFirst()));
//                        String currentCata = helper.getOnlyDigits(itemLine.replaceAll("<.*?>", ""));
//                        compare = helper.compareCata(currentCata, lastCata);
//                    }
//                    if (compare < 0) {
//                        //当前目录位于上一个解析的目录之前
//                        itemLine = itemLine.replaceAll("<p", "<h5").replaceAll("</p>", "</h5>");
//                        itemLine = itemLine.replaceAll("<title>", "<h5>").replaceAll("</title>", "</h5>");
//                        chapter.insert(0, itemLine.trim() + "\n");
//                        ChapterCata chapterCata = new ChapterCata();
//                        chapterCata.setCata(itemLine.trim());
//                        chapterCata.setContent(chapter.toString());
//                        chapterCata.setId(UuidUtil.get32UUID());
//                        chapterList.addFirst(chapterCata);
//                        cataList.addFirst(itemLine.trim());
//                        chapter = new StringBuilder();
//                    } else {
//                        chapter.insert(0, itemLine.trim());
//                    }
//                } else {
//                    //非目录
//                    warpperLine(itemLine, entity, chapter);
//                }
//            } else {
//                warpperLine(itemLine, entity, chapter);
//            }
//        }
//        if (chapter.length() > 0) {
//            ChapterCata chapterCata = new ChapterCata();
//            chapterCata.setCata("<h5>正文</h5>");
//            chapterCata.setContent(chapter.toString());
//            chapterCata.setId(UuidUtil.get32UUID());
//            chapterList.addFirst(chapterCata);
//            cataList.addFirst("<h5>正文</h5>");
//        }
//        if (!chapterList.isEmpty()) {
//            entity.setChapter("0");
//            res.put("chapterList", chapterList);
//        }
//    }

//    private void warpperLine(String itemLine, KnowledgeItem entity, StringBuilder chapter) {
//        net.cnki.cscp.task.HprdcpXmlProcessorHelper helper = new net.cnki.cscp.task.HprdcpXmlProcessorHelper();
//        //1.纯数字，大概率是页码或者单独的其他数字
//        /*if (text.matches("-?\\d+(\\.\\d+)?")) {
//            continue;
//        }*/
//        //2.大概率是页眉
//        if ((itemLine.contains("版次") || itemLine.contains("版本")) && itemLine.contains("/")) {
//            itemLine = "";
//        }
//        if (StringUtils.isNotEmpty(itemLine.trim())) {
//            //知识链接
//            Pattern drawing = Pattern.compile("(?![\\d]+$)(?![A-Z]+$)[0-9A-Z]{15,}");
//            Matcher drawingM = drawing.matcher(itemLine.trim());
//            while (drawingM.find()) {
//                try {
//                    itemLine = itemLine.replaceAll(drawingM.group(), "<a class=\"hyperlink\">" + drawingM.group() + "</a>");
//                } catch (Exception e) {
//                    itemLine = hyperlink(itemLine, drawingM.group());
//                }
//            }
//            //书名
//            Pattern book = Pattern.compile("《.*?》");
//            Matcher bookM = book.matcher(itemLine.trim());
//            while (bookM.find()) {
//                try {
//                    itemLine = itemLine.replaceAll(bookM.group(), "<a class=\"hyperlink\">" + bookM.group() + "</a>");
//                } catch (Exception e) {
//                    itemLine = hyperlink(itemLine, bookM.group());
//                }
//            }
//        }
//        if (itemLine.contains("<image")) {
//            //图片、表格解析
//            if (itemLine.contains("<image") && itemLine.contains("href")) {
//                /*if(itemLine.contains("\"table\"")){
//                    //表格
//                    String tableName = getImgName(itemLine);
//                    String outPutPath = entity.getOutPutPath();
//                    if(StringUtils.isNotEmpty(outPutPath)){
//                        itemLine = helper.readExcelToHtml(itemLine, outPutPath +TABLEDIR + File.separator + tableName + TABLEFIX);
//                    }
//                }else{
//                    //图片
//                    itemLine = itemLine.trim();
//                    String imgName = getImgName(itemLine);
//                    if(StringUtils.isNotEmpty(imgName)){
//                        itemLine = "\n<img href=\"javascript:;\" src=\"" + entity.getPicPath().get(imgName) + "\" />\n";
//                    }
//                }*/
//                String name = getImgName(itemLine);
//                String excelStr = helper.readExcelToHtml(itemLine, entity.getOutPutPath() + TABLEDIR + File.separator + name + TABLEFIX);
//                if (StringUtils.isNotEmpty(excelStr)) {
//                    //表格
//                    itemLine = excelStr;
//                } else {
//                    //图片
//                    if (StringUtils.isNotEmpty(name)) {
//                        itemLine = "\n<img href=\"javascript:;\" src=\"" + entity.getPicPath().get(name) + "\" />\n";
//                    }
//                }
//            }
//        }
//        if (StringUtils.isNotEmpty(itemLine)) {
//            chapter.insert(0, itemLine.trim());
//        }
//    }

    /**
     * 从字符串中获取图片的名称
     *
     * @param itemLine <image href="images/2_44000.jpg" placement="break">
     *                 <image href="\images\81-image7.jpg" type="" placement="break" />
     *                 <image id="37" type="table" href="images/node_2_03700.jpg" placement="break" i-width="560" i-height="690" p-width="761" p-height="1077"><alt>表1 可行性研究报告所需主要支持性文件</alt></image>
     * @return
     */
    private String getImgName(String itemLine) {
        StringBuilder name = new StringBuilder();
        int end = itemLine.indexOf(".jpg");
        end = end > 0 ? end : itemLine.indexOf(".JPG");
        end = end > 0 ? end : itemLine.indexOf(".png");
        end = end > 0 ? end : itemLine.indexOf(".PNG");
        end = end > 0 ? end : itemLine.indexOf(".jpeg");
        end = end > 0 ? end : itemLine.indexOf(".JPEG");
        end = end > 0 ? end : itemLine.indexOf(".emf");//html不支持
        for (int i = end - 1; i > 0; i--) {
            if (itemLine.charAt(i) == '/' || itemLine.charAt(i) == '\\') {
                break;
            } else {
                name.insert(0, itemLine.charAt(i));
            }
        }
        return name.toString();
        /*int start = itemLine.indexOf("<image href=\"")+"<image href=\"".length();
        int end = 0;
        for(int i = start;i < itemLine.length();i++){
            if(itemLine.charAt(i) == '"'){
                end = i;
                break;
            }
        }
        if(end > 0){
            String name = itemLine.substring(start,end);
            name = name.replaceAll("\\\\","").replaceAll("/","")
                    .replaceAll("images","").replaceAll(".jpg","")
                    .replaceAll(".png","").replaceAll(".jpeg","");
            return name;
        }*/
    }

    /**
     * 超链接替换
     *
     * @param itemLine
     * @param group
     * @return
     */
    private String hyperlink(String itemLine, String group) {
        return itemLine.substring(0, itemLine.indexOf(group)) + "<a class=\"hyperlink\">" + group + "</a>" + itemLine.substring(itemLine.indexOf(group) + group.length());
    }

    /**
     * 校验文件是否重复入库
     *
     * @param databaseCode 专题库的编码
     * @param desFile      目标待校验的文件
     * @return
     */
//    public boolean checkFileExistedOrNot(String databaseCode, File desFile) {
//        IDataContext context = SpringUtils.getBean(IDataContext.class);
//        List<Map<String, String>> fileList = context.excuteQueryList("select id from " + databaseCode + "_metadata where md5 = '" + MD5.md5File(desFile) + "' and del_flag = 0");
//        return !fileList.isEmpty();
//    }

//
//    /**
//     * 执行文件碎片化程序
//     *
//     * @param toolPath      碎片化工具的存放路径
//     * @param xmlOutputPath 解析结果的输出路径
//     * @param os            碎片化工具的执行环境
//     * @param file          待碎片化的文件
//     */
//    public boolean executeFragCMD(String toolPath, String xmlOutputPath, String os, File file) {
//        try {
//            String frag = buildCmd(FRAG, toolPath, file.getAbsolutePath(), xmlOutputPath);
//            log.info("{}---开始执行frag命令:{}", file.getName(), frag);
//            // execute the fragment command.
//            String result = WINDOW.equals(os) ? ShellUtil.execWindows(frag) : ShellUtil.execLinux(frag);
//            log.info("{}---执行frag命令结束:{}", file.getName(), result);
//
//            // we don't care the kind of file, just fragment it.
//            //if (".pdf".equals(ext)) {//word类型文件无需执行export命令
//            String export = buildCmd(EXPORT, toolPath, file.getAbsolutePath(), xmlOutputPath);
//            log.info("{}---开始执行export命令{}", file.getName(), export);
//            log.info("{}---执行export命令结束{}", file.getName(), WINDOW.equals(os) ? ShellUtil.execWindows(export) : ShellUtil.execLinux(export));
//            //}
//            return true;
//        } catch (Exception e) {
//            log.error("执行碎片化命令失败：" + e.getMessage(), e);
//            e.printStackTrace();
//        }
//        return false;
//    }

    /**
     * 拼接碎片化的命令
     *
     * @param type       区分frag命令还时export命令
     * @param toolPath   碎片化工具的存放路径
     * @param inputPath  带碎片化文件的输入目录
     * @param outputPath 碎片化完成的结果的输出目录
     * @return
     */
    String buildCmd(String type, String toolPath, String inputPath, String outputPath) {
        //D:\project\doc-process-x86\dp frag --type="doc" --input="D:\project\test.pdf"
        //D:\project\doc-process-x86\dp export --product="general" --result-type="xml" --input="D:\project\test.pdf" --output="D:\transfer\output"
        if ("frag".equals(type)) {
            return toolPath + File.separator + "dp frag --type=\"doc\" --input=\"" + inputPath + "\" --output=\"" + outputPath + "\"";
        } else {
            return toolPath + File.separator + "dp export --product=\"general\" --result-type=\"xml\" --input=\"" + inputPath + "\" --output=\"" + outputPath + "\"";
        }
    }

//    /**
//     * 导入的源文件存minio
//     *
//     * @param folder 存储minio的目标目录文件夹
//     * @param file   导入的源文件
//     * @param entity 存放数据对象
//     */
//    public void uploadFileToServer(String folder, MultipartFile file, YfbMaterialFile entity) {
//        try {
//            log.info("文件{}--准备上传minio,路径{}", file.getOriginalFilename(), folder);
//            RemoteFileService fileService = SpringUtils.getBean(RemoteFileService.class);
//            Resp<SysFile> upload = fileService.uploadWithFolder(folder, file);
//            if (upload.getData() != null) {
//                SysFile data = upload.getData();
//                entity.setFilePath(data.getUrl());
//                log.info("文件{}--上传minio成功:{}", file.getOriginalFilename(), data.getUrl());
//            } else {
//                throw new RuntimeException(upload.getMsg());
//            }
//        } catch (Exception e) {
//            log.error("文件{}--上传minio失败{}", file.getOriginalFilename(), e.getMessage());
//            e.printStackTrace();
//            throw e;
//        }
//    }
//
//    /**
//     * 文档数据存es
//     *
//     * @param materialName 素材名称
//     */
//    public void handleES(String materialName, YfbMaterialFile entity) {
//        Map<String, Object> knowledgeDoc = new HashMap<>();
//        knowledgeDoc.put("fileId", entity.getMfileId());
//        knowledgeDoc.put("materialId", entity.getMaterialId());
//        knowledgeDoc.put("materialLibId", entity.getMlibId());
//        knowledgeDoc.put("fileName", entity.getMaterialName());
//        knowledgeDoc.put("fileContent", entity.getFileContent());
//        knowledgeDoc.put("fileSummary", entity.getFileSummary());
//        knowledgeDoc.put("fileTags", entity.getFileTags());
//        knowledgeDoc.put("fileType", entity.getFileType());
//        knowledgeDoc.put("fileSize", entity.getFileSize());
//        knowledgeDoc.put("secret", entity.getSecurityLevel());
//        knowledgeDoc.put("secretStr", entity.getSecurityLevelStr());
//        knowledgeDoc.put("fileUrl", entity.getFileUrl());
//        knowledgeDoc.put("remark", entity.getFileRemark());
//        knowledgeDoc.put("isShare", CommonConstants.ShareStatus.NOT.getStatus());
//        knowledgeDoc.put("source", materialName);
//        knowledgeDoc.put("createTime", DateUtils.getTime());
//        knowledgeDoc.put("createBy", this.userId);
//        knowledgeDoc.put("deleteFlag", CommonConstants.DataStatus.NORMAL.getStatus());
//        ESContext client = SpringUtils.getBean(ESContext.class);
//        Environment environment = SpringUtils.getBean(Environment.class);
//        String prefix = environment.getProperty("knowledge.create.prefix");
//        client.addDocument(CommonConstants.INDEX_PREFIX + prefix + CommonConstants.PERSONAL_INDEX, String.valueOf(entity.getMfileId()), knowledgeDoc);
//    }
//
//    /**
//     * 组建知识索引文档结构
//     *
//     * @param databaseCode
//     * @param client
//     * @param knowledgeDoc
//     * @param i
//     * @param chapterCata
//     */
//    private void putKnowledgeDoc(String databaseCode, ESContext client, Map<String, Object> knowledgeDoc, int i, ChapterCata chapterCata) {
//        Set<String> mapping = client.getMapping(CommonConstants.INDEX_PREFIX + databaseCode.toLowerCase());
//        if (!mapping.contains(CommonConstants.SECTION_PREFIX + i)) {
//            //创建新的mapping
//            ESBuilder builder = ESBuilder.builder().build().buildString(CommonConstants.SECTION_PREFIX + i);
//            client.addMapping(CommonConstants.INDEX_PREFIX + databaseCode.toLowerCase(), builder.getMapping());
//        }
//        knowledgeDoc.put(CommonConstants.SECTION_PREFIX + i, JSON.toJSONString(chapterCata));
//    }
//
//    /**
//     * 保存碎片化索引文档
//     *
//     * @param databaseCode
//     * @param client
//     * @param fragDoc
//     * @param chapterCata
//     */
//    private void saveFragDoc(String databaseCode, ESContext client, Map<String, Object> fragDoc, ChapterCata chapterCata) {
//        IKnowledgeGraphService graphService = SpringUtils.getBean(IKnowledgeGraphService.class);
//        SysKeywordParam param = new SysKeywordParam();
//        param.setContent(chapterCata.getContent());
//        SysKeywordMap keywordMap = graphService.getKeywordMapByParam(param);
//        String keyWords = keywordMap.getKeywordList().stream().map(SysKeyword::getKeyWord).collect(Collectors.joining(","));
//        String fragId = UuidUtil.get32UUID();
//        fragDoc.put("id", fragId);
//        fragDoc.put("keyword", keyWords);
//        fragDoc.put("chapter", chapterCata.getContent());
//        fragDoc.put("catalog_name", chapterCata.getCata());
//        client.addDocument(CommonConstants.FRAG_PREFIX + databaseCode.toLowerCase(), fragId, fragDoc);
//    }
//
//    /**
//     * 删除meta表数据
//     *
//     * @param databaseCode
//     * @param desFile
//     */
//    public void deleteMaterialFile(String databaseCode, File desFile) {
//        KnowledgeItemMapper itemMapper = SpringUtils.getBean(KnowledgeItemMapper.class);
//        itemMapper.deleteMetaByMd5(databaseCode + "_metadata", MD5.md5File(desFile), new Date());
//    }
//
//
//    /**
//     * 恢复文档为未删除状态
//     *
//     * @param materialFileId
//     */
//    public void recoverMaterialFile(long materialFileId) {
//        YfbMaterialFileMapper itemMapper = SpringUtils.getBean(YfbMaterialFileMapper.class);
//        itemMapper.batchCompleteDeleteRecover(new Long[]{materialFileId},2L,1);
//    }

    /**
     * the keyword parameter.
     */
    private class KeywordParam {
        /**
         * the database code.
         */
        String databaseCode;
        /**
         * doc id.
         */
        Long docId = null;
        /**
         * file id.
         */
        Long fileId = null;
        /**
         * text content.
         */
        String fileContent;
        /**
         * file name.
         */
        String fileName;
        /**
         * file MD5.
         */
        String fileMD5;
        /**
         * the xml content.
         */
        String xmlContent;
        /**
         * current date.
         */
        Date currentDate;
        /**
         * the pic path array.
         */
        Map<String, String> picPath;
        /**
         * file path.
         */
        String filePath;
        /**
         * fraged.
         */
        String fraged;
        /**
         * secret.
         */
        Integer secret;
        /**
         * chapter.
         */
        String chapter;
    }

//    /**
//     * 文件数据入mysql库
//     *
//     * @param materialFile
//     * @return
//     */
//    @Transactional
//    public void handleMysql(int taskid) {
//        YfbMaterialFileMapper itemMapper = SpringUtils.getBean(YfbMaterialFileMapper.class);
//        // update knowledge metadata.
//        this.updateKnowledgeMetadata(itemMapper, materialFile);
//    }

//    /**
//     * save book name as keyword. all book name is keyword.
//     *
//     * @param bookNameList book name list.
//     */
//    private int saveBookNameAsKeyword(List<SysKeyword> bookNameList) {
//        int affectedCount = 0;
//        // if the program found book in content, save the book as keyword.
//        if (null != bookNameList && bookNameList.size() > 0) {
//            IKeywordService keywordService = SpringUtils.getBean(IKeywordService.class);
//            for (SysKeyword word : bookNameList) {
//                affectedCount = affectedCount + keywordService.insertKeyword(word.getKeyWord(), null, SysKeywordType.HPR.code);
//            }
//
//            if (affectedCount > 0) {
//                // cost long time, care to invoke the  reload method.
//                IKnowledgeGraphService graphService = SpringUtils.getBean(IKnowledgeGraphService.class);
//                graphService.reloadSysKeyword();
//            }
//        }
//        return affectedCount;
//    }

//    /**
//     * save knowledge metadata.
//     *
//     * @param itemMapper   the knowledge item mapper.
//     * @param materialFile
//     */
//    private void updateKnowledgeMetadata(YfbMaterialFileMapper itemMapper, YfbMaterialFile materialFile) {
//        log.info("文档[{}]所属素材[{}]正在更新库[{}]", materialFile.getMaterialName(), materialFile.getMaterialId(), materialFile.getMlibId());
//        itemMapper.updateYfbMaterialFile(materialFile);
//    }
//
//    /**
//     * save knowledge metadata file keyword.
//     *
//     * @param itemMapper knowledge item mapper.
//     * @param materialId the material id
//     * @param fileMD5    the file md5.
//     * @param keywords
//     */
//    private void saveKnowledgeMetadataFileKeyword(YfbMaterialFileMapper itemMapper, Long materialId, String fileMD5, List<SysKeyword> keywords) {
//        //batch insert the keywords.
//        List<KnowledgeMetadataFileKeyword> fileKeywordList = new ArrayList<>();
//        for (SysKeyword sysKeyword : keywords) {
//            KnowledgeMetadataFileKeyword keyword = new KnowledgeMetadataFileKeyword();
//            keyword.setKeyword(sysKeyword.getKeyWord());
//            keyword.setWordType(sysKeyword.getWordType());
//            keyword.setFileMD5(fileMD5);
//            keyword.setFileId(materialId);
//            keyword.setFrequency(sysKeyword.getFrequency());
//            keyword.setCreateBy(this.userId.toString());
//            keyword.setCreateTime(new Date());
//            keyword.setUpdateBy(this.userId.toString());
//            keyword.setUpdateTime(new Date());
//            keyword.setDelFlag(0);
//            fileKeywordList.add(keyword);
//        }
//        // batch insert keyword.
//        if (fileKeywordList.size() > 0) {
//            itemMapper.batchInsertKnowledgeMetadataFileKeyword(fileKeywordList);
//        }
//    }
//
//    /**
//     * save knowledge metadta file keyword relationship.
//     *
//     * @param itemMapper knowledge item mapper.
//     * @param param      the keyword parameter.
//     */
//    private void saveKnowledgeMetadataFileKeywordRelationship(KnowledgeItemMapper itemMapper, KeywordParam param) {
//        // batch insert the keywords relationships.
//        if (StringUtils.isNotEmpty(param.fileContent)) {
//            IKnowledgeGraphService graphService = SpringUtils.getBean(IKnowledgeGraphService.class);
//            SysKeywordParam sysKeywordParam = new SysKeywordParam();
//            sysKeywordParam.setContent(param.fileContent);
//            SysKeywordMap keywordMap = graphService.getKeywordMapByParam(sysKeywordParam);
//            List<SysKeywordRnsp> rnspList = keywordMap.getRelationshipList();
//
//            List<KnowledgeMetadataFileKeywordRel> relList = new ArrayList<>();
//            for (SysKeywordRnsp rnsp : rnspList) {
//                KnowledgeMetadataFileKeywordRel rel = new KnowledgeMetadataFileKeywordRel();
//                rel.setFileId(param.fileId);
//                rel.setFileName(param.fileName);
//                rel.setFileMD5(param.fileMD5);
//                rel.setSource(rnsp.getSource());
//                rel.setTarget(rnsp.getTarget());
//                rel.setFrequency(rnsp.getFrequency());
//                rel.setDistance(rnsp.getDistance());
//                rel.setRelation(rnsp.getRelation());
//                rel.setCreateBy(this.userId.toString());
//                rel.setCreateTime(new Date());
//                rel.setUpdateBy(this.userId.toString());
//                rel.setUpdateTime(new Date());
//                rel.setDelFlag(0);
//                relList.add(rel);
//            }
//            // batch insert relationship.
//            if (relList.size() > 0) {
//                itemMapper.batchInsertKnowledgeMetadataFileKeywordRelationship(relList);
//            }
//        }
//    }

    /**
     * 读取文件并转为字符串
     *
     * @param stream 待读取的文件
     * @return
     */
    private String fileStreamtostr(InputStream stream) {

        XWPFDocument xwpfDocument = null;
        try {
            xwpfDocument = new XWPFDocument(stream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(xwpfDocument);
        String text = xwpfWordExtractor.getText();
        return text;
        /*StringBuffer res = new StringBuffer();
        List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
        for (XWPFParagraph p : paragraphs) {
            res.append(p.getText());
        }
        return res.toString();*/
        /*if (stream == null) {
            return null;
        }

        BufferedReader reader = null;
        StringBuffer res = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(stream,StandardCharsets.ISO_8859_1));
            String line;
            while ((line = reader.readLine()) != null) {
                res.append(line).append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("读取文件失败" + e.getMessage());
            return "";
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return res.toString();*/
    }

//    /**
//     * 批量导入完成后更新导入状态
//     *
//     * @param materialLibId
//     */
//    public void updateImportStatus(Long materialLibId) {
//        IDataContext context = SpringUtils.getBean(IDataContext.class);
//        context.excuteUpdate("update sys_cms_database set import_status = 0 where DATABASECODE = '" + materialLibId + "'");
//    }
//
//    /**
//     * 批量导入完成后更新数量
//     *
//     * @param materialLibId 素材库id
//     * @param count         此次新增数量
//     */
//    public void updateDatabaseRecordCount(Long materialLibId, int count) {
//        YfbMaterialLibMapper mapper = SpringUtils.getBean(YfbMaterialLibMapper.class);
//        mapper.updateMaterialLibCapacityCount(materialLibId, count, "add");
//    }
//
//    /**
//     * 批量导入完成后更新知识体系节点的文档数量
//     *
//     * @param syscode 知识体系节点code
//     * @param count   此次新增数量
//     */
//    public void updateStructureTypeRecordCount(String syscode, int count) {
//        IDataContext context = SpringUtils.getBean(IDataContext.class);
//        context.excuteUpdate("update sys_knowledge_structure_type set record_num = record_num + " + count + " where syscode = '" + syscode + "'");
//    }
//
//    /**
//     * 批量导入完成后更新知识体系节点的文档数量
//     *
//     * @param syscode 知识体系节点code
//     * @param count   此次新增数量
//     */
//    public void updateStructureTypeRedisCount(String syscode, int count) {
//        KnowledgeService service = SpringUtils.getBean(KnowledgeService.class);
//        service.updateClassSystemRedis(syscode, "add", count);
//    }

}
